﻿using System;
using System.Linq;
using System.Xml.Linq;

namespace ServiceHost
{
    public class TownHelper
    {
        //http://api.geonames.org/findNearby?lat=-25&lng=139&username=briteapps&featureClass=P&maxRows=10&radius=300
        public static Town[] GetNearByTowns(Coordinate coordinate)
        {
            //Get all towns
            var towns = GetAllNearByTowns(coordinate);

            //Filter out not suitable towns
            var filteredTowns = from e in towns
                                where e.Coordinate.Distance(coordinate) > Const.TownMinDistance
                                select e;

            return filteredTowns.ToArray();
        }

        public static Town[] GetAllNearByTowns(Coordinate coordinate)
        {
            const string sUrl =
                "http://api.geonames.org/findNearby?lat={0}&lng={1}&username=briteapps&featureClass=P&maxRows={2}&radius={3}";

            string apiUrl = string.Format(sUrl, coordinate.Y, coordinate.X, Const.NumberOfTowns, Const.MaxDistance);

            var feedXml = XDocument.Load(apiUrl);

            var towns = from element in feedXml.Descendants("geoname")
                        select new Town()
                                   {
                                       Name = element.Element("name").Value,
                                       Distance = Double.Parse(element.Element("distance").Value),
                                       Coordinate =
                                           new Coordinate
                                               {
                                                   X = Double.Parse(element.Element("lng").Value),
                                                   Y = Double.Parse(element.Element("lat").Value)
                                               }
                                   };

            return towns.ToArray();
        }
    }
}